package com.baiyangtx.lingerweather;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

import com.baiyangtx.lingerweather.adapt.CityKey;
import com.baiyangtx.lingerweather.model.CityBasicImformationAdapt;
import com.baiyangtx.lingerweather.service.DataService;
import com.baiyangtx.lingerweather.view.AddCityButton;
import com.baiyangtx.lingerweather.view.CityMangeButton;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;

public class CityMangerActivity extends Activity {

	private Context context = this ;
	
	private GridView gridView ;
	
	private DataService mService ;
	
	private static final int REQUEST_CODE_CITYCHOOSE = 11 ;
	
	
	ArrayList<Map<String,String>> list ;
	private final ServiceConnection mConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			DataService.MBinder mBinder = (DataService.MBinder)service ;
			mService = mBinder.getService() ;
			updateList() ;
			gridView.setAdapter(new CityAdapt()) ;
			gridView.invalidate() ;
		}
	};
	
	
	private class CityAdapt extends BaseAdapter {
		
		
		private static final int baseId = 0x10010 ;
		
		private final AddCityButton addButton = new AddCityButton(context) ;

		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if( convertView != null ){
				return convertView ;
			}
			
			if( position == list.size() ){
				return addButton ;
			}
			CityMangeButton button = new CityMangeButton(context) ;
			button.setCityInformation(new CityBasicImformationAdapt(context, list.get(position))) ;
			return button ;
		}
		
		@Override
		public long getItemId(int position) {
			return baseId + position ;
		}
		
		@Override
		public Object getItem(int position) {
			if( position < list.size() ){
				return list.get(position) ;
			}else{
				return null ;
			}
		}
		
		@Override
		public int getCount() {
			int size = list.size() + 1 ;
			return size ;
		}
	};
	
	
	
	private final OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, 
				View view, 
				int position,
				long id) {
			if( position == parent.getCount() - 1 ){
				Intent intent = new Intent(context, CityChooseActivity.class ) ;
				startActivityForResult(intent, REQUEST_CODE_CITYCHOOSE ) ;
			}else{
				Intent result = new Intent() ;
				@SuppressWarnings("unchecked")
				Map<String,String> map = (Map<String, String>) parent.getItemAtPosition(position) ;
				result.putExtra( CityKey.CITY_CODE , map.get(CityKey.CITY_CODE) ) ;
				result.putExtra( CityKey.CITY_NAME , map.get(CityKey.CITY_NAME) ) ;
				setResult(RESULT_OK, result) ;
				finish();
			}
		}
	};
	
	
	
	
	private final OnItemLongClickListener longClick = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			if( position != parent.getCount() ){
				System.out.println("Position : " + position);
				String name = list.get(position).get(CityKey.CITY_NAME) ;
				final int index = position ;
				new AlertDialog.Builder(CityMangerActivity.this).setTitle("删除城市")
					.setMessage("删除城市：" + name + "?" )
					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String code = list.get(index).get(CityKey.CITY_CODE) ;
							mService.deleteCity(code) ;
							updateList() ;
							gridView.setAdapter(new CityAdapt() );
						}
					})
					.setNegativeButton("取消", null).show() ;
			}
			return true ;
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.requestWindowFeature( Window.FEATURE_NO_TITLE ) ;
		Intent intent = new Intent(this , DataService.class ) ;
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE) ;
		setContentView(R.layout.city_manage);
		
		gridView = (GridView) findViewById(R.id.city_manger_grid);
		gridView.setOnItemClickListener(listener) ;
		gridView.setOnItemLongClickListener(longClick) ;
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT)) ;
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if( resultCode == RESULT_OK && requestCode == REQUEST_CODE_CITYCHOOSE ){
			String code = data.getStringExtra(CityKey.CITY_CODE ) ;
			String name = data.getStringExtra(CityKey.CITY_NAME ) ;
			System.out.println("Name : " + name + " Code : " + code );
			for( Map<String,String> m :list ){
				if( m.get(CityKey.CITY_CODE).equals(code) ){
					return ;
				}
			}
			mService.addCity(code, name) ;
			updateList() ;
			gridView.setAdapter( new CityAdapt() );
//			CityAdapt adapt = (CityAdapt)gridView.getAdapter() ;
//			adapt.notifyDataSetChanged() ;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	@Override
	protected void onDestroy() {
		unbindService(mConnection) ;
		super.onDestroy();
	}
	
	private void updateList(){
		Set<Map<String,String>> set = mService.listAllUserCities() ;
		list = new ArrayList<Map<String,String>>() ;
		for(Map<String,String> m : set ){
			list.add(m) ;
		}
	}
}
